/**
 * 初始化整体流量图标
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
    var zrnumber = require('echarts/util/number');

    var myChart = ec.init(document.getElementById('cityCmp_chart')); 

    var option_day = {

            tooltip : {
                trigger: 'axis'
            },
            legend: {
                data:['北京精准','上海精准']
            },
            toolbox: {
                show : true,
                orient:'vertical',
                feature : {
                    mark : {show: true},
                    dataZoom : {show: true},
                    magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                    restore : {show: true},
                    saveAsImage : {show: true}
                }
            },
            calculable : true,
            xAxis: [{
                type: "category",
                 boundaryGap: true,
                data:[''],
                axisLabel:{formatter:function(value){
                    return value;
                }}
            }],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            dataZoom: {
                show: true,
                start: 90
            },
            series: [
                {
                    name: 'PC',
                    type: 'line',
                    smooth: true,
                    symbol:"none",
                    itemStyle: {normal: {areaStyle: {type: 'default'}}},
                    data:[]
                }
            ]
    };

    var nameMap={"jingzhun":"精准", "zhiding":"置顶", "zhineng":"智能"};
    //[city1, city2]
    var cityArr = [];
    var legend_1 = [];
    function setLegendNameMap(cityCmp_citys,proType){
        cityArr =cityCmp_citys;
        legend_1 = [];
        $.each(cityArr,function(i,city){
            var city_index_1 = city + nameMap[proType];
            legend_1.push(city_index_1);
        });    
        option_day.legend.data = legend_1;
    }

    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    function show(businessName,eventType){
        var dateGrp = $('#cityCmpOption').attr('dateGrp');
        var statType = $('#cityCmpOption').attr('statType');

        var proType = $("input:radio:checked[name='proType_city']").val();
        var cityCmp_citys = $('#cityCmp_citys').val().split(",");
        var index = $('#index_cityCmp').val();
        if(cityCmp_citys.length != 2){
            alert("必须选择两个对比城市!");
            return;
        }
        setLegendNameMap(cityCmp_citys,proType);
        myChart.showLoading({ text: '正在努力的读取数据中...' });
        $.ajax({
            url: '/dashboard/income/ajax/netflow/cityCmp',
            type: 'post',
            async: true,
            data:{"businessName":businessName,"dateGroup":dateGrp,"statType":statType,"index":index,"proType":proType,"city1":cityArr[0],"city2":cityArr[1]},
            dataType: 'json',
            success: function(data, textStatus) {
                //X轴时间
                option_day.xAxis[0].data = data.time;
                //上图每条曲线
                var i = 0;
                var series_local = [];
                $.each(cityArr,function(i,city){
                    //上图每条曲线
                    series_local[i] = {
                        name: legend_1[i],
                        type: 'line',
                        smooth: true,
                        symbol:"none",
                        'data': data[city]
                    };
                });

                option_day.tooltip.formatter=tooltipFunc_1;
                //数据
                option_day.series = series_local;

                //区域缩放
                var datezoom_local={
                    stat_date:{start:(1-31/data.time.length)*100,end:100},
                    week_begin:{start:(1-12/data.time.length)*100,end:100},
                    month_num:{start:0,end:100},
                };
                //少于31个点，全显
                if(data.time.length<31){
                    datezoom_local={
                        stat_date:{start:0,end:100},
                        week_begin:{start:0,end:100},
                        month_num:{start:0,end:100},
                    };
                }

                if(eventType == 1 || eventType == 2){
                    if('stat_date'==dateGrp || 'week_begin'==dateGrp){      
                        option_day.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                    }else if('month_num'==dateGrp){
                        option_day.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                    }
                   
                    option_day.dataZoom=datezoom_local[dateGrp];
                    option_day.dataZoom.show=true;
                    if(eventType == 1 && myChart.component.dataZoom){
                        myChart.component.dataZoom.absoluteZoom(datezoom_local[dateGrp]);
                    }
                    myChart.setOption(option_day,true);
                }
                // myChart.clear();
                myChart.hideLoading();
            },
            error : function() {
                myChart.hideLoading();
            }
        });
    }

    //鼠标click事件
    var ecConfig = require('echarts/config');
    function eventClick(param){
        var click_date = '2014-01-01';
        if (typeof param.seriesIndex != 'undefined') {
            click_date = param.name;
        }else{
            return;
        }
        loadTableData(click_date);
    }
    myChart.on(ecConfig.EVENT.CLICK, eventClick);

 //加载27个直销城市当天的数据，, 0:字符, 1:数字, 2:百分比
    var show_cols = {"city_name":0,"cost":1,"cost_chain":2,"pv":1,"pv_chain":2,"adpv":1,"adpv_chain":2,"pvr":3,"pvr_chain":2,"disp":1,"disp_chain":2,
    "click":1,"click_chain":2,"asn":1,"asn_chain":2,"acp":1,"acp_chain":2,"ctr2":3,"ctr2_chain":2};
   function loadTableData(stat_date){
        var dateGrp = $('#cityCmpOption').attr('dateGrp');
        var statType = $('#cityCmpOption').attr('statType');
        var businessName = cate;
        $.ajax({
            url: '/dashboard/income/ajax/netflow/cityProduct',
            type: 'post',
            async: true,
            data:{"dateGroup":dateGrp,"statType":statType,"dateVal":stat_date, "businessName":businessName,"dataType":"table"},
            dataType: 'json',
            success: function(data, textStatus) {
                var resultList = data.dataList;
                var htmlRows = "";
                $.each(resultList,function(i,vo){
                    htmlRows += "<tr>";

                    $.each(show_cols,function(col,colType){
                        switch(colType){
                            case 0:
                                htmlRows += "<td>";
                                htmlRows += vo[col];
                                htmlRows += "</td>";
                                break;
                            case 1:
                                htmlRows += "<td>";
                                htmlRows += zrnumber.addCommas(vo[col]);
                                htmlRows += "</td>";
                                break;
                            case 2:
                                htmlRows += getRate(vo[col]);
                                break;
                            case 3:
                                htmlRows += "<td>";
                                htmlRows += parseFloat(vo[col]).toFixed(2)+"%";
                                htmlRows += "</td>";
                                break;                                
                        }
                    });

                    htmlRows += "</tr>";
                });

                $('#cityCmpTable tr:gt(0)').remove();
                $('#cityCmpTable_date').text(stat_date.replace(/\-/g,"."));
                $('#cityCmpTable').append(htmlRows);
            },
            error : function() {

            }
        }); 
    }

    function tooltipFunc_1(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,0);
    }
    function tooltipFunc_2(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,1);
    }
    //提示框
    function  tooltipFunc(params, ticket, callback,optionIndex){
        var dateVal = formatShowDate(params[0].name);
        var curOption = option_day;
        var index_current=getIndexByName(curOption.xAxis[0].data,params[0].name);

        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        var isStatDay = isDay(); 
        if(isStatDay)
            result += getWeekDay(dateVal);
        result += '</td><td>占比</td>';
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek())
            result += "<td>周环比</td>";
         else if(isMonth())
            result += "<td>月环比</td>";
        result += '</tr>';

        var total=0;

        $(params).each(function(index,para){
            total+=parseFloat(para.data);
        });

        $(params).each(function(index,para){
            var s=((para.data/total)*100).toFixed(2);
            result+='<tr><td>'+para.seriesName+'</td><td>'+zrnumber.addCommas(para.data)+'</td><td>'+s+'%</td>';

            var seriesIndex = para.seriesIndex;
            var day_td="<td>--</td>";
            //日周月 环比(前一日周月)
            if(index_current-1>=0){
                var data_yesday = null;
                
                data_yesday= curOption.series[seriesIndex].data[index_current-1];                
                
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(s>0){
                        day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
            }
            result += day_td;
            //周同比(日)
            if(isStatDay){
                var week_td='<td>--</td>';
                if(index_current-7>=0){
                    data_week= curOption.series[seriesIndex].data[index_current-7];
                    var s=(((para.data/data_week)-1)*100).toFixed(2);
                    if(s>0){
                        week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
                result += week_td;
            }
            result += '</tr>';
        });
        result+='</table>';
        return result;
    }           

   function formatShowDate(yyyymmdd){
        var dateGrp = $('#cityCmpOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return yyyymmdd;
        }else if('week_begin'==dateGrp){
            return yyyymmdd;
        }else if('month_num'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
    }

    function isDay(){
        var dateGrp = $('#cityCmpOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return true;
        }
        return false;
    }

    function isWeek(){
         var dateGrp = $('#cityCmpOption').attr('dateGrp');
        if('week_begin'==dateGrp){
            return true;
        }
        return false;
    }

    function isMonth(){
        var dateGrp = $('#cityCmpOption').attr('dateGrp');
        if('month_num'==dateGrp){
            return true;
        }
        return false;
    }

    var zrUtil = require('zrender/tool/util');
    // console.log(zrUtil);

    function getShowDays(){
        return myChart.component.dataZoom.option.xAxis[0].data;
    }

    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }

    function formatTime(time){
        return time;
    }

    function getAllDays(){
        return option_day.xAxis.data||option_day.xAxis[0].data;
    }


    $(function(){
        $("#cityCmp_mul").multiselect({
            header:false,
            height:300,
            minWidth:140,
            noneSelectedText: "--请选择--",
            checkAllText: "disabled",
            uncheckAllText: '清空',
            selectedList:2,
            click: function(event, ui){
                var array_of_checked_values = $("#cityCmp_mul").multiselect("getChecked").map(function(){
                   return this.value;    
                }).get();
                var warning = $(".message");
                if(array_of_checked_values.length > 2){
                    return false;
                }
                 // $("#cityCmp_citys").val(array_of_checked_values.join(","));
            },
            uncheckAll: function(){
                $("#cityCmp_citys").val('');
            },
            selectedText: function(numChecked, numTotal, checkedItems){
                var two='';
                /*
                    js数组的map方法和 $.map(arr,callback)将一个数组中的元素转换到另一个数组中;
                    $(selector).map(arr,callback)返回jquery对象 $(selector).map(arr,callback).get()使用 get() 来处理返回的对象以得到基础的数组
                */
               if(numChecked > 2){
                        return false;
                }
                var idcs=checkedItems.map(function(element){
                    return element.value; 
                });
                $("#cityCmp_citys").val(idcs.join(','));

                return idcs.join(' , ');
            }
       });
    }); 


    //绑定chenge事件
    $("#index_cityCmp").change(function(){
        changeIndex(this);
    });

    //绑定书刷新按钮点击事件
    $("#refreshCityCmp_btn").click(function(){
        var type = 2;
        EC.show(cate,type);
    });

    $(":button.btnCityCmp[dateGrp]").click(function(){
        changeDateGrp(this);
        EC.show(cate,1);
    });

    var EC={
        show:show,
        resize:function(){myChart.resize();},
        getShowDays:getShowDays,
        getAllDays:getAllDays
    };
    
    return EC;
});

